// i18next 后端配置 (v25+)
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
import middleware from 'i18next-http-middleware';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 初始化 i18next
export const initI18n = async () => {
  const instance = i18next.createInstance();
  
  await instance
    .use(Backend)
    .use(middleware.LanguageDetector)
    .init({
      // 语言检测配置
      detection: {
        order: ['querystring', 'cookie', 'header'],
        lookupQuerystring: 'lang',
        lookupCookie: 'i18next',
        lookupHeader: 'accept-language',
        caches: ['cookie']
      },
      
      // 后端配置 - 从文件系统加载翻译文件
      backend: {
        loadPath: path.join(__dirname, '../../../locales/{{lng}}.json'),
        addPath: path.join(__dirname, '../../../locales/{{lng}}.missing.json')
      },
      
      // 支持的语言
      supportedLngs: ['zh-CN', 'en-US', 'ja-JP', 'ko-KR'],
      fallbackLng: 'zh-CN',
      
      // 命名空间配置
      ns: ['translation'],
      defaultNS: 'translation',
      
      // 调试模式
      debug: process.env.NODE_ENV === 'development',
      
      // 其他配置
      saveMissing: true,
      saveMissingTo: 'current',
      interpolation: {
        escapeValue: false
      },
      
      // 预加载语言
      preload: ['zh-CN', 'en-US'],
      
      // v25+ 新配置选项
      compatibilityJSON: 'v4', // 保持与旧版本兼容
      
      // 资源加载配置
      partialBundledLanguages: true,
      
      // 更新检查
      updateMissing: true
    });
  
  return instance;
};

// 获取 i18next 实例
let i18nInstance = null;

export const getI18nInstance = async () => {
  if (!i18nInstance) {
    i18nInstance = await initI18n();
  }
  return i18nInstance;
};

// 导出中间件
export const i18nMiddleware = async (req, res, next) => {
  const instance = await getI18nInstance();
  return middleware.handle(instance)(req, res, next);
};

// 导出翻译函数
export const t = async (key, options) => {
  const instance = await getI18nInstance();
  return instance.t(key, options);
};

// 获取支持的语言列表
export const getSupportedLanguages = async () => {
  const instance = await getI18nInstance();
  return instance.options.supportedLngs || ['zh-CN', 'en-US'];
};

// 获取当前语言
export const getCurrentLanguage = (req) => {
  return req.language || 'zh-CN';
};

// 更改语言
export const changeLanguage = async (lng) => {
  const instance = await getI18nInstance();
  return instance.changeLanguage(lng);
};

export default i18next;